﻿<#
    Script  : ImportPSModule
    Author  : Riwut Libinuko
    Blog    : http://blog.libinuko.com 
    Copyright :© IdeasFree - cakriwut@gmail.com, 2013. All rights reserved.
#>

function GetLatestNugetExe
{
   param (
     $installLocation 
   )
   $outputFile = Join-Path $installLocation nuget.exe
   $webClient.DownloadFile("https://nuget.org/nuget.exe", $outputFile);
   return (gci $installLocation -recurse -filter "nuget.exe" | sort LastWriteTime -Descending | select -First 1).FullName;
}

function GetPackageInfo
{
   param (
     [string] $ModuleDirectory
   )
   
   if(!(Test-Path $ModuleDirectory))
   {
      return $null
   }

   $pkgLocation = gi $ModuleDirectory
   # Check if we can find package version info in the directoryname
   if($pkgLocation.Name -match "(?<PkgName>.+[^(\.\d)])\.(?<PkgVer>(\d\.){1,}(\d))`$")
   { 
      $pkgLocation.Name -match "(?<PkgName>.+[^(\.\d)])\.(?<PkgVer>(\d\.){1,}(\d))`$" |%  { 
                           if($matches["PkgVer"] -ne $null)
                           {
                              $version = ($matches["PkgVer"]).Trim()
                           } else {
                              $version = "0.0.0.0"
                           }
                           new-object PSObject -prop @{              
                             Name =($matches["PkgName"]).Trim();
                             Version= $version;
                           }}
   } else {
     $nugetPkg = gci $ModuleDirectory -Recurse -Filter "*.nupkg" | sort LastWriteTime -Descending | select -first 1
	 if($nugetPkg.Name -match "(?<PkgName>.+[^(\.\d)])\.(?<PkgVer>(\d\.){1,}(\d))\.nupkg`$")
	 {
	     $nugetPkg.Name -match "(?<PkgName>.+[^(\.\d)])\.(?<PkgVer>(\d\.){1,}(\d))\.nupkg`$" |%  { 
                           if($matches["PkgVer"] -ne $null)
                           {
                              $version = ($matches["PkgVer"]).Trim()
                           } else {
                              $version = "0.0.0.0"
                           }
                           new-object PSObject -prop @{              
                             Name =($matches["PkgName"]).Trim();
                             Version= $version;
                           }}
	 } else {
	     $nuspecXml = GetNuspecContent $nugetPkg.FullName
		 New-Object PSObject -Prop @{
		 			Name =($nuspecXml.ContentXml.package.metadata.id).Trim();
					Version = ($nuspecXml.ContentXml.package.metadata.version).Trim();
		       }
	 }
   }   
}
